package com.example.show_auto.ui.components

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.show_auto.data.MultiUserDataManager
import org.burnoutcrew.reorderable.ReorderableItem
import org.burnoutcrew.reorderable.detectReorder
import org.burnoutcrew.reorderable.rememberReorderableLazyListState
import org.burnoutcrew.reorderable.reorderable

/**
 * 用户切换弹窗
 * 参考图一中的保存方案弹窗样式
 */
@Composable
fun UserSwitchDialog(
    users: List<MultiUserDataManager.UserData>,
    currentUser: String?,
    onSwitchUser: (MultiUserDataManager.UserData) -> Unit,
    onDeleteUser: (MultiUserDataManager.UserData) -> Unit,
    onUpdateUserName: (String, String) -> Unit, // (oldName, newName) -> Unit
    onReorderUsers: (List<MultiUserDataManager.UserData>) -> Unit, // 用户重新排序回调
    onDismiss: () -> Unit,
    multiUserDataManager: MultiUserDataManager
) {
    var showDeleteConfirmDialog by remember { mutableStateOf(false) }
    var userToDelete by remember { mutableStateOf<MultiUserDataManager.UserData?>(null) }
    
    // 用于收集所有待保存的用户名修改
    var pendingNameChanges by remember { mutableStateOf<Map<String, String>>(emptyMap()) }
    
    // 编辑状态管理 - 记录哪个用户正在编辑
    var editingUser by remember { mutableStateOf<String?>(null) }
    
    // 可拖拽的用户列表状态
    var reorderableUsers by remember { mutableStateOf(users) }
    val reorderState = rememberReorderableLazyListState(onMove = { from, to ->
        // 禁止移动当前用户（第一位）
        val fromUser = reorderableUsers.getOrNull(from.index)
        val toUser = reorderableUsers.getOrNull(to.index)
        
        // 如果拖拽的是当前用户，或者想要移动到当前用户的位置，则不允许
        if (fromUser?.userName != currentUser && to.index != 0) {
            reorderableUsers = reorderableUsers.toMutableList().apply {
                add(to.index, removeAt(from.index))
            }
        }
    })
    
    // 当users列表更新时，同步更新reorderableUsers
    LaunchedEffect(users) {
        reorderableUsers = users
    }
    
    val focusManager = LocalFocusManager.current
    
    // 辅助函数：清除焦点并保存所有待保存的修改
    fun clearFocusAndSave() {
        pendingNameChanges.forEach { (oldUserName, newUserName) ->
            if (newUserName.isNotBlank() && newUserName != oldUserName) {
                onUpdateUserName(oldUserName, newUserName)
            }
        }
        focusManager.clearFocus()
        pendingNameChanges = emptyMap()
        editingUser = null
        
        // 保存拖拽后的顺序
        if (reorderableUsers != users) {
            onReorderUsers(reorderableUsers)
        }
    }
    
    AlertDialog(
        onDismissRequest = {
            clearFocusAndSave()
            onDismiss()
        },
        title = { 
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                Text(
                    text = "切换用户", 
                    fontSize = 18.sp, 
                    fontWeight = FontWeight.Bold
                )
                Text(
                    text = "点击用户名修改名字",
                    fontSize = 12.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    fontWeight = FontWeight.Normal
                )
            }
        },
        text = {
            // 添加点击监听的容器，点击空白区域时清除焦点并保存
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable(
                        indication = null,
                        interactionSource = remember { MutableInteractionSource() }
                    ) {
                        clearFocusAndSave()
                    }
            ) {
                if (users.isEmpty()) {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(200.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        Text("暂无保存的用户数据", color = MaterialTheme.colorScheme.onSurfaceVariant)
                    }
                } else {
                    LazyColumn(
                        state = reorderState.listState,
                        modifier = Modifier
                            .heightIn(max = 280.dp)
                            .reorderable(reorderState)
                    ) {
                        items(reorderableUsers, key = { it.userName }) { user ->
                            ReorderableItem(reorderState, key = user.userName) { isDragging ->
                                Card(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(vertical = 4.dp),
                                    colors = CardDefaults.cardColors(
                                        containerColor = if (user.userName == currentUser) {
                                            MaterialTheme.colorScheme.primaryContainer
                                        } else {
                                            Color(0xFFE3F2FD)
                                        }
                                    ),
                                    elevation = CardDefaults.cardElevation(
                                        defaultElevation = if (isDragging) 6.dp else 2.dp
                                    )
                                ) {
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(12.dp),
                                    horizontalArrangement = Arrangement.SpaceBetween,
                                    verticalAlignment = Alignment.CenterVertically
                                ) {
                                    // 左侧：用户信息，不可点击切换
                                    Column(
                                        modifier = Modifier
                                            .weight(1f)
                                            .padding(end = 8.dp)
                                    ) {
                                        // 用户名显示/编辑
                                        if (editingUser == user.userName) {
                                            // 编辑模式：显示输入框
                                            SmallTextField(
                                                value = pendingNameChanges[user.userName] ?: user.userName,
                                                onValueChange = { newName ->
                                                    // 收集待保存的修改
                                                    pendingNameChanges = pendingNameChanges.toMutableMap().apply {
                                                        if (newName != user.userName) {
                                                            put(user.userName, newName)
                                                        } else {
                                                            remove(user.userName)
                                                        }
                                                    }
                                                },
                                                onValueCommit = { newName ->
                                                    if (newName.isNotBlank() && newName != user.userName) {
                                                        onUpdateUserName(user.userName, newName)
                                                        // 清除已保存的待保存状态
                                                        pendingNameChanges = pendingNameChanges.toMutableMap().apply {
                                                            remove(user.userName)
                                                        }
                                                    }
                                                    editingUser = null
                                                },
                                                widthDp = 110.dp
                                            )
                                        } else {
                                            // 显示模式：显示文本，点击进入编辑
                                            Text(
                                                text = user.userName,
                                                fontWeight = FontWeight.Medium,
                                                fontSize = 14.sp,
                                                modifier = Modifier
                                                    .clickable {
                                                        editingUser = user.userName
                                                    }
                                                    .padding(horizontal = 8.dp, vertical = 4.dp)
                                            )
                                        }
                                    }
                                    
                                    // 右侧：操作按钮和拖拽按钮
                                    Row(
                                        verticalAlignment = Alignment.CenterVertically,
                                        horizontalArrangement = Arrangement.spacedBy(4.dp)
                                    ) {
                                        // 切换按钮
                                        OutlinedButton(
                                            onClick = { 
                                                if (user.userName != currentUser) {
                                                    clearFocusAndSave()
                                                    onSwitchUser(user)
                                                }
                                            },
                                            modifier = Modifier
                                                .height(28.dp)
                                                .widthIn(min = 45.dp, max = 55.dp),
                                            contentPadding = PaddingValues(horizontal = 4.dp, vertical = 0.dp),
                                            enabled = user.userName != currentUser
                                        ) {
                                            Text(
                                                text = if (user.userName == currentUser) "当前" else "切换",
                                                fontSize = 10.sp,
                                                maxLines = 1
                                            )
                                        }
                                        
                                        // 删除按钮
                                        OutlinedButton(
                                            onClick = { 
                                                clearFocusAndSave()
                                                userToDelete = user
                                                showDeleteConfirmDialog = true
                                            },
                                            modifier = Modifier
                                                .height(28.dp)
                                                .widthIn(min = 45.dp, max = 55.dp),
                                            contentPadding = PaddingValues(horizontal = 4.dp, vertical = 0.dp),
                                            colors = ButtonDefaults.outlinedButtonColors(
                                                contentColor = MaterialTheme.colorScheme.error
                                            ),
                                            border = BorderStroke(1.dp, MaterialTheme.colorScheme.error)
                                        ) {
                                            Text("删除", fontSize = 10.sp, maxLines = 1)
                                        }
                                        
                                        // 拖拽按钮（当前用户不显示拖拽按钮，因为永远在第一位）
                                        if (user.userName != currentUser) {
                                            Icon(
                                                imageVector = Icons.Default.Menu,
                                                contentDescription = "拖拽排序",
                                                tint = MaterialTheme.colorScheme.primary,
                                                modifier = Modifier
                                                    .detectReorder(reorderState)
                                                    .padding(4.dp)
                                            )
                                        } else {
                                            // 为当前用户保留相同的空间，但不显示拖拽按钮
                                            Spacer(modifier = Modifier.padding(4.dp).size(24.dp))
                                        }
                                    }
                                }
                            }
                            }
                        }
                    }
                }
            }
        },
        confirmButton = {
            TextButton(onClick = {
                clearFocusAndSave()
                onDismiss()
            }) {
                Text("关闭")
            }
        }
    )
    
    // 删除确认弹窗
    if (showDeleteConfirmDialog && userToDelete != null) {
        AlertDialog(
            onDismissRequest = { showDeleteConfirmDialog = false },
            title = { Text("确认删除") },
            text = { 
                Text("删除用户「${userToDelete!!.userName}」将永久删除该用户的所有数据，确定要继续吗？") 
            },
            confirmButton = {
                Button(
                    onClick = {
                        onDeleteUser(userToDelete!!)
                        showDeleteConfirmDialog = false
                    },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.error
                    )
                ) {
                    Text("删除")
                }
            },
            dismissButton = {
                TextButton(onClick = { showDeleteConfirmDialog = false }) {
                    Text("取消")
                }
            }
        )
    }
}

/**
 * 用户操作选择弹窗
 * 参考图二中的操作选择弹窗样式
 */
@Composable
fun UserActionChoiceDialog(
    currentUserName: String?,
    onNewUser: () -> Unit,
    onUpdateCurrent: () -> Unit,
    onDismiss: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("选择操作", fontSize = 18.sp, fontWeight = FontWeight.Bold) },
        text = {
            Column {
                Text("请选择要执行的操作：", fontSize = 14.sp)
                Spacer(modifier = Modifier.height(16.dp))
                
                // 新增玩家数据按钮
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable { onNewUser() },
                    colors = CardDefaults.cardColors(containerColor = Color(0xFFE3F2FD))
                ) {
                    Row(
                        modifier = Modifier.padding(16.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            imageVector = Icons.Default.Add,
                            contentDescription = "新增玩家数据",
                            tint = MaterialTheme.colorScheme.primary
                        )
                        Spacer(modifier = Modifier.width(12.dp))
                        Column {
                            Text("新增玩家数据", fontWeight = FontWeight.Medium)
                            Text("创建一个新的玩家数据", fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
                        }
                    }
                }
                
                Spacer(modifier = Modifier.height(8.dp))
                
                // 更新当前玩家数据按钮
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable { onUpdateCurrent() },
                    colors = CardDefaults.cardColors(containerColor = Color(0xFFE3F2FD))
                ) {
                    Row(
                        modifier = Modifier.padding(16.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            imageVector = Icons.Default.KeyboardArrowUp,
                            contentDescription = "更新当前玩家数据",
                            tint = MaterialTheme.colorScheme.primary
                        )
                        Spacer(modifier = Modifier.width(12.dp))
                        Column {
                            Text("更新当前玩家数据", fontWeight = FontWeight.Medium)
                            Text(
                                if (currentUserName != null) "更新「$currentUserName」的数据" else "更新当前数据",
                                fontSize = 12.sp, 
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }
                }
            }
        },
        confirmButton = {},
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
}

/**
 * 用户名输入弹窗
 */
@Composable
fun UserNameInputDialog(
    onConfirm: (String) -> Unit,
    onDismiss: () -> Unit,
    existingUserNames: List<String> = emptyList()
) {
    var userName by remember { mutableStateOf("") }
    var showError by remember { mutableStateOf(false) }
    var errorMessage by remember { mutableStateOf("") }
    
    fun validateUserName(name: String): Boolean {
        return when {
            name.isBlank() -> {
                errorMessage = "用户名不能为空"
                false
            }
            name.length > 6 -> {
                errorMessage = "用户名不能超过6个字符"
                false
            }
            existingUserNames.contains(name) -> {
                errorMessage = "用户名已存在"
                false
            }
            else -> true
        }
    }
    
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("输入玩家名称", fontSize = 18.sp, fontWeight = FontWeight.Bold) },
        text = {
            Column {
                Text("请输入新玩家的名称：", fontSize = 14.sp)
                Spacer(modifier = Modifier.height(16.dp))
                
                OutlinedTextField(
                    value = userName,
                    onValueChange = { newValue ->
                        // 限制最多6个字符
                        if (newValue.length <= 6) {
                            userName = newValue
                            showError = false
                        }
                    },
                    label = { Text("玩家名称") },
                    placeholder = { Text("请输入玩家名称") },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                    isError = showError,
                    supportingText = {
                        Text("${userName.length}/6", fontSize = 10.sp, color = Color.Gray)
                    },
                    keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
                    keyboardActions = KeyboardActions(
                        onDone = {
                            if (validateUserName(userName)) {
                                onConfirm(userName)
                            } else {
                                showError = true
                            }
                        }
                    )
                )
                
                if (showError) {
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = errorMessage,
                        color = MaterialTheme.colorScheme.error,
                        fontSize = 12.sp
                    )
                }
            }
        },
        confirmButton = {
            Button(
                onClick = {
                    if (validateUserName(userName)) {
                        onConfirm(userName)
                    } else {
                        showError = true
                    }
                },
                enabled = userName.isNotBlank()
            ) {
                Text("确定")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
}

/**
 * 小型可编辑文本框组件
 * 参考ComprehensiveQueryPage中的SmallTextField实现
 */
@Composable
private fun SmallTextField(
    value: String,
    onValueChange: (String) -> Unit,
    onValueCommit: (String) -> Unit = {}, // 当输入完成时触发
    widthDp: Dp = 120.dp,
    modifier: Modifier = Modifier
) {
    var internalValue by remember { mutableStateOf(value) }
    var isFocused by remember { mutableStateOf(false) }
    val focusRequester = remember { FocusRequester() }
    val focusManager = LocalFocusManager.current

    LaunchedEffect(value) { internalValue = value }

    BasicTextField(
        value = internalValue,
        onValueChange = { newValue ->
            // 限制最多6个字符
            if (newValue.length <= 6) {
                internalValue = newValue
                onValueChange(newValue)
            }
        },
        modifier = modifier
            .width(widthDp)
            .height(24.dp)
            .background(Color.White, RoundedCornerShape(6.dp))
            .border(
                width = 1.dp, 
                color = if (isFocused) MaterialTheme.colorScheme.primary else Color(0xFF90A4AE), 
                shape = RoundedCornerShape(6.dp)
            )
            .focusRequester(focusRequester)
            .onFocusChanged { focusState ->
                val wasFocused = isFocused
                isFocused = focusState.isFocused
                // 当失去焦点时，触发保存
                if (wasFocused && !isFocused) {
                    if (internalValue.isNotBlank() && internalValue != value) {
                        onValueCommit(internalValue)
                    }
                }
            }
            .clickable(
                indication = null,
                interactionSource = remember { MutableInteractionSource() }
            ) {
                focusRequester.requestFocus()
            }
            .pointerInput(Unit) {
                detectTapGestures(
                    onTap = { 
                        // 阻止点击事件传播到父容器
                        focusRequester.requestFocus()
                    }
                )
            },
        textStyle = TextStyle(
            color = Color.Black, 
            fontSize = 12.sp, 
            textAlign = TextAlign.Center,
            fontWeight = FontWeight.Medium
        ),
        singleLine = true,
        keyboardOptions = KeyboardOptions(
            keyboardType = KeyboardType.Text,
            imeAction = ImeAction.Done
        ),
        keyboardActions = KeyboardActions(
            onDone = {
                if (internalValue.isNotBlank() && internalValue != value) {
                    onValueCommit(internalValue)
                }
                focusManager.clearFocus()
            }
        ),
        cursorBrush = SolidColor(Color.Black),
        decorationBox = { innerTextField ->
            Box(
                contentAlignment = Alignment.Center,
                modifier = Modifier
                    .fillMaxSize()
                    .padding(horizontal = 4.dp)
            ) {
                innerTextField()
            }
        }
    )
} 